package com.rbac.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.common.Result;
import com.rbac.entity.SysRole;
import com.rbac.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 角色管理控制器
 *
 * @author rbac-system
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色管理")
public class SysRoleController {

    @Autowired
    private SysRoleService roleService;

    @GetMapping("/page")
    @ApiOperation("分页查询角色")
    @PreAuthorize("hasAuthority('role:query')")
    public Result<IPage<SysRole>> page(
            @ApiParam("页码") @RequestParam(defaultValue = "1") Integer current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") Integer size,
            @ApiParam("角色名称") @RequestParam(required = false) String roleName,
            @ApiParam("角色编码") @RequestParam(required = false) String roleCode,
            @ApiParam("状态") @RequestParam(required = false) Integer status) {
        
        Page<SysRole> page = new Page<>(current, size);
        IPage<SysRole> result = roleService.page(page, roleName, roleCode, status);
        return Result.success(result);
    }

    @GetMapping("/list")
    @ApiOperation("查询角色列表")
    @PreAuthorize("hasAuthority('role:query')")
    public Result<List<SysRole>> list() {
        List<SysRole> list = roleService.list();
        return Result.success(list);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID查询角色")
    @PreAuthorize("hasAuthority('role:query')")
    public Result<SysRole> getById(@ApiParam("角色ID") @PathVariable Long id) {
        SysRole role = roleService.getById(id);
        if (role == null) {
            return Result.error("角色不存在");
        }
        return Result.success(role);
    }

    @PostMapping
    @ApiOperation("创建角色")
    @PreAuthorize("hasAuthority('role:add')")
    public Result<String> create(@Valid @RequestBody SysRole role) {
        // 检查角色编码是否已存在
        if (roleService.existsByRoleCode(role.getRoleCode())) {
            return Result.error("角色编码已存在");
        }
        
        boolean success = roleService.save(role);
        return success ? Result.success("创建成功") : Result.error("创建失败");
    }

    @PutMapping("/{id}")
    @ApiOperation("更新角色")
    @PreAuthorize("hasAuthority('role:edit')")
    public Result<String> update(@ApiParam("角色ID") @PathVariable Long id, @Valid @RequestBody SysRole role) {
        role.setId(id);
        
        // 检查角色编码是否被其他角色使用
        if (roleService.existsByRoleCodeAndIdNot(role.getRoleCode(), id)) {
            return Result.error("角色编码已被其他角色使用");
        }
        
        boolean success = roleService.updateById(role);
        return success ? Result.success("更新成功") : Result.error("更新失败");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除角色")
    @PreAuthorize("hasAuthority('role:delete')")
    public Result<String> delete(@ApiParam("角色ID") @PathVariable Long id) {
        boolean success = roleService.removeById(id);
        return success ? Result.success("删除成功") : Result.error("删除失败");
    }

    @PostMapping("/{id}/permissions")
    @ApiOperation("分配权限")
    @PreAuthorize("hasAuthority('role:edit')")
    public Result<String> assignPermissions(@ApiParam("角色ID") @PathVariable Long id,
                                         @ApiParam("权限ID列表") @RequestBody List<Long> permissionIds) {
        boolean success = roleService.assignPermissionsToRole(id, permissionIds);
        return success ? Result.success("分配成功") : Result.error("分配失败");
    }

    @PostMapping("/{id}/menus")
    @ApiOperation("分配菜单")
    @PreAuthorize("hasAuthority('role:edit')")
    public Result<String> assignMenus(@ApiParam("角色ID") @PathVariable Long id,
                                   @ApiParam("菜单ID列表") @RequestBody List<Long> menuIds) {
        boolean success = roleService.assignMenusToRole(id, menuIds);
        return success ? Result.success("分配成功") : Result.error("分配失败");
    }

    @GetMapping("/{id}/permissions")
    @ApiOperation("查询角色权限")
    @PreAuthorize("hasAuthority('role:query')")
    public Result<List<Long>> getPermissions(@ApiParam("角色ID") @PathVariable Long id) {
        List<Long> permissionIds = roleService.getPermissionIdsByRoleId(id);
        return Result.success(permissionIds);
    }

    @GetMapping("/{id}/menus")
    @ApiOperation("查询角色菜单")
    @PreAuthorize("hasAuthority('role:query')")
    public Result<List<Long>> getMenus(@ApiParam("角色ID") @PathVariable Long id) {
        List<Long> menuIds = roleService.getMenuIdsByRoleId(id);
        return Result.success(menuIds);
    }
}
